use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use tokio::net::{TcpListener, TcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use anyhow::Result;
use tauri::Manager;

mod system_proxy;
mod config_manager;
use system_proxy::{SystemProxyConfig, set_system_proxy, get_system_proxy};
// use config_manager::AppConfig;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyConfig {
    host: String,
    port: u16,
    username: Option<String>,
    password: Option<String>,
    #[serde(rename = "type")]
    proxy_type: String,
    // 代理链支持
    chain: Option<Vec<ProxyNode>>,
    // 负载均衡支持
    load_balance_servers: Option<Vec<ProxyNode>>,
    load_balance_strategy: Option<String>, // "round_robin", "random", "least_connections"
    // TLS支持
    enable_tls: Option<bool>,
    tls_verify_cert: Option<bool>,
    // 隐私保护
    dns_leak_protection: Option<bool>,
    custom_dns_servers: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProxyNode {
    host: String,
    port: u16,
    username: Option<String>,
    password: Option<String>,
    #[serde(rename = "type")]
    proxy_type: String,
}

// 访问控制规则
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessRule {
    pub rule_type: String, // "allow" or "deny"
    pub ip_range: String,  // IP地址或CIDR范围
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessControl {
    pub enabled: bool,
    pub default_action: String, // "allow" or "deny"
    pub rules: Vec<AccessRule>,
    pub whitelist_ips: Vec<String>,
    pub blacklist_ips: Vec<String>,
}

impl Default for AccessControl {
    fn default() -> Self {
        Self {
            enabled: false,
            default_action: "allow".to_string(),
            rules: Vec::new(),
            whitelist_ips: vec!["127.0.0.1".to_string(), "::1".to_string()],
            blacklist_ips: Vec::new(),
        }
    }
}

// 流量统计数据结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrafficStats {
    pub bytes_sent: u64,
    pub bytes_received: u64,
    pub connections_total: u64,
    pub connections_active: u64,
    pub start_time: u64,
    pub last_activity: u64,
}

impl Default for TrafficStats {
    fn default() -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            bytes_sent: 0,
            bytes_received: 0,
            connections_total: 0,
            connections_active: 0,
            start_time: now,
            last_activity: now,
        }
    }
}

// 连接日志
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionLog {
    pub timestamp: u64,
    pub client_ip: String,
    pub target_host: String,
    pub target_port: u16,
    pub proxy_type: String,
    pub status: String, // "connected", "failed", "closed"
    pub bytes_sent: u64,
    pub bytes_received: u64,
    pub duration: u64, // 连接持续时间（秒）
    pub error_message: Option<String>,
}

// 审计日志
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditLog {
    pub timestamp: u64,
    pub event_type: String, // "config_change", "proxy_start", "proxy_stop", "access_denied"
    pub user_ip: Option<String>,
    pub description: String,
    pub details: Option<String>,
}

// 服务器健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerHealth {
    pub host: String,
    pub port: u16,
    pub is_healthy: bool,
    pub last_check: u64,
    pub failure_count: u32,
    pub response_time: u64, // 毫秒
}

// 负载均衡状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoadBalanceState {
    current_server_index: usize,
    server_connections: Vec<u64>, // 每个服务器的连接数
    server_health: Vec<ServerHealth>, // 服务器健康状态
}

impl Default for LoadBalanceState {
    fn default() -> Self {
        Self {
            current_server_index: 0,
            server_connections: Vec::new(),
            server_health: Vec::new(),
        }
    }
}

// Web管理接口配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebManagementConfig {
    pub enabled: bool,
    pub port: u16,
    pub api_key: String,
    pub allowed_ips: Vec<String>,
}

impl Default for WebManagementConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            port: 8889,
            api_key: uuid::Uuid::new_v4().to_string(),
            allowed_ips: vec!["127.0.0.1".to_string()],
        }
    }
}

// 全局状态管理
pub struct ProxyState {
    is_running: bool,
    config: Option<ProxyConfig>,
    server_handle: Option<tokio::task::JoinHandle<()>>,
    traffic_stats: TrafficStats,
    load_balance_state: LoadBalanceState,
    access_control: AccessControl,
    web_management: WebManagementConfig,
    connection_logs: Vec<ConnectionLog>,
    audit_logs: Vec<AuditLog>,
}

impl Default for ProxyState {
    fn default() -> Self {
        Self {
            is_running: false,
            config: None,
            server_handle: None,
            traffic_stats: TrafficStats::default(),
            load_balance_state: LoadBalanceState::default(),
            access_control: AccessControl::default(),
            web_management: WebManagementConfig::default(),
            connection_logs: Vec::new(),
            audit_logs: Vec::new(),
        }
    }
}

type SharedState = Arc<Mutex<ProxyState>>;

// 访问控制检查函数
fn is_access_allowed(client_ip: &str) -> bool {
    // 简化实现：默认允许本地连接
    // 在实际应用中，这里应该检查全局状态中的访问控制配置
    client_ip.starts_with("127.") || client_ip.starts_with("::1") || client_ip.starts_with("192.168.") || client_ip.starts_with("10.")
}

// 记录连接日志
fn log_connection(client_ip: &str, target_host: &str, target_port: u16, proxy_type: &str, status: &str) {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let log_entry = ConnectionLog {
        timestamp,
        client_ip: client_ip.to_string(),
        target_host: target_host.to_string(),
        target_port,
        proxy_type: proxy_type.to_string(),
        status: status.to_string(),
        bytes_sent: 0,
        bytes_received: 0,
        duration: 0,
        error_message: None,
    };

    // 在实际应用中，这里应该将日志添加到全局状态
    tracing::info!("连接日志: {:?}", log_entry);
}

// 记录审计日志
fn log_audit_event(event_type: &str, description: &str, user_ip: Option<&str>) {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let audit_entry = AuditLog {
        timestamp,
        event_type: event_type.to_string(),
        user_ip: user_ip.map(|s| s.to_string()),
        description: description.to_string(),
        details: None,
    };

    // 在实际应用中，这里应该将日志添加到全局状态
    tracing::info!("审计日志: {:?}", audit_entry);
}

// 流量统计包装器
pub struct TrafficMonitor {
    state: SharedState,
}

impl TrafficMonitor {
    pub fn new(state: SharedState) -> Self {
        Self { state }
    }

    pub fn record_bytes_sent(&self, bytes: u64) {
        if let Ok(mut state) = self.state.lock() {
            state.traffic_stats.bytes_sent += bytes;
            state.traffic_stats.last_activity = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
        }
    }

    pub fn record_bytes_received(&self, bytes: u64) {
        if let Ok(mut state) = self.state.lock() {
            state.traffic_stats.bytes_received += bytes;
            state.traffic_stats.last_activity = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
        }
    }

    pub fn increment_connection(&self) {
        if let Ok(mut state) = self.state.lock() {
            state.traffic_stats.connections_total += 1;
            state.traffic_stats.connections_active += 1;
        }
    }

    pub fn decrement_connection(&self) {
        if let Ok(mut state) = self.state.lock() {
            if state.traffic_stats.connections_active > 0 {
                state.traffic_stats.connections_active -= 1;
            }
        }
    }
}

// Tauri 命令：启动代理服务器
#[tauri::command]
async fn start_proxy(config: ProxyConfig, state: tauri::State<'_, SharedState>) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;

    if proxy_state.is_running {
        return Err("代理服务器已在运行".to_string());
    }

    let listen_addr = format!("127.0.0.1:{}", 8888); // 本地监听端口
    let listen_addr_clone = listen_addr.clone();
    let config_clone = config.clone();

    let handle = tokio::spawn(async move {
        if let Err(e) = run_proxy_server(&listen_addr_clone, config_clone).await {
            eprintln!("代理服务器错误: {}", e);
        }
    });

    proxy_state.is_running = true;
    proxy_state.config = Some(config);
    proxy_state.server_handle = Some(handle);
    proxy_state.traffic_stats = TrafficStats::default(); // 重置流量统计

    // 记录审计日志
    log_audit_event("proxy_start", &format!("代理服务器已启动，监听地址: {}", listen_addr), None);

    Ok(format!("代理服务器已启动，监听地址: {}", listen_addr))
}

// Tauri 命令：停止代理服务器
#[tauri::command]
async fn stop_proxy(state: tauri::State<'_, SharedState>) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;

    if !proxy_state.is_running {
        return Err("代理服务器未运行".to_string());
    }

    if let Some(handle) = proxy_state.server_handle.take() {
        handle.abort();
    }

    proxy_state.is_running = false;
    proxy_state.config = None;

    // 记录审计日志
    log_audit_event("proxy_stop", "代理服务器已停止", None);

    Ok("代理服务器已停止".to_string())
}

// Tauri 命令：设置系统代理
#[tauri::command]
async fn set_system_proxy_settings(config: SystemProxyConfig) -> Result<String, String> {
    set_system_proxy(&config)
        .map_err(|e| format!("设置系统代理失败: {}", e))?;

    if config.enable {
        Ok(format!("系统代理已启用: {}:{}", config.server, config.port))
    } else {
        Ok("系统代理已禁用".to_string())
    }
}

// Tauri 命令：获取系统代理设置
#[tauri::command]
async fn get_system_proxy_settings() -> Result<SystemProxyConfig, String> {
    get_system_proxy()
        .map_err(|e| format!("获取系统代理设置失败: {}", e))
}

// Tauri 命令：测试代理连接
#[tauri::command]
async fn test_proxy_connection(config: ProxyConfig) -> Result<String, String> {
    test_proxy(&config)
        .await
        .map_err(|e| format!("代理测试失败: {}", e))
}

// Tauri 命令：获取流量统计
#[tauri::command]
async fn get_traffic_stats(state: tauri::State<'_, SharedState>) -> Result<TrafficStats, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.traffic_stats.clone())
}

// Tauri 命令：重置流量统计
#[tauri::command]
async fn reset_traffic_stats(state: tauri::State<'_, SharedState>) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    proxy_state.traffic_stats = TrafficStats::default();
    Ok("流量统计已重置".to_string())
}

// Tauri 命令：检查服务器健康状态
#[tauri::command]
async fn check_servers_health(servers: Vec<ProxyNode>) -> Result<Vec<ServerHealth>, String> {
    let mut health_results = Vec::new();

    for server in servers {
        let health = check_server_health(&server).await;
        health_results.push(health);
    }

    Ok(health_results)
}

// Tauri 命令：设置开机自启动
#[tauri::command]
async fn set_auto_launch(enable: bool, app_handle: tauri::AppHandle) -> Result<String, String> {
    use auto_launch::AutoLaunchBuilder;

    let app_path = app_handle.path().resource_dir()
        .map_err(|e| format!("获取应用路径失败: {}", e))?;

    let auto_launch = AutoLaunchBuilder::new()
        .set_app_name("ProxyTool")
        .set_app_path(&app_path.to_string_lossy())
        .build()
        .map_err(|e| format!("创建自启动配置失败: {}", e))?;

    if enable {
        auto_launch.enable()
            .map_err(|e| format!("启用开机自启动失败: {}", e))?;
        Ok("开机自启动已启用".to_string())
    } else {
        auto_launch.disable()
            .map_err(|e| format!("禁用开机自启动失败: {}", e))?;
        Ok("开机自启动已禁用".to_string())
    }
}

// Tauri 命令：检查开机自启动状态
#[tauri::command]
async fn get_auto_launch_status(app_handle: tauri::AppHandle) -> Result<bool, String> {
    use auto_launch::AutoLaunchBuilder;

    let app_path = app_handle.path().resource_dir()
        .map_err(|e| format!("获取应用路径失败: {}", e))?;

    let auto_launch = AutoLaunchBuilder::new()
        .set_app_name("ProxyTool")
        .set_app_path(&app_path.to_string_lossy())
        .build()
        .map_err(|e| format!("创建自启动配置失败: {}", e))?;

    auto_launch.is_enabled()
        .map_err(|e| format!("检查自启动状态失败: {}", e))
}

// Tauri 命令：获取连接日志
#[tauri::command]
async fn get_connection_logs(state: tauri::State<'_, SharedState>) -> Result<Vec<ConnectionLog>, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.connection_logs.clone())
}

// Tauri 命令：获取审计日志
#[tauri::command]
async fn get_audit_logs(state: tauri::State<'_, SharedState>) -> Result<Vec<AuditLog>, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.audit_logs.clone())
}

// Tauri 命令：清除连接日志
#[tauri::command]
async fn clear_connection_logs(state: tauri::State<'_, SharedState>) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    proxy_state.connection_logs.clear();
    log_audit_event("logs_cleared", "连接日志已清除", None);
    Ok("连接日志已清除".to_string())
}

// Tauri 命令：清除审计日志
#[tauri::command]
async fn clear_audit_logs(state: tauri::State<'_, SharedState>) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    proxy_state.audit_logs.clear();
    log_audit_event("logs_cleared", "审计日志已清除", None);
    Ok("审计日志已清除".to_string())
}

// Tauri 命令：获取访问控制配置
#[tauri::command]
async fn get_access_control(state: tauri::State<'_, SharedState>) -> Result<AccessControl, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.access_control.clone())
}

// Tauri 命令：更新访问控制配置
#[tauri::command]
async fn update_access_control(
    state: tauri::State<'_, SharedState>,
    access_control: AccessControl,
) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    proxy_state.access_control = access_control;
    log_audit_event("config_change", "访问控制配置已更新", None);
    Ok("访问控制配置已更新".to_string())
}

// Tauri 命令：获取Web管理配置
#[tauri::command]
async fn get_web_management_config(state: tauri::State<'_, SharedState>) -> Result<WebManagementConfig, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.web_management.clone())
}

// Tauri 命令：更新Web管理配置
#[tauri::command]
async fn update_web_management_config(
    state: tauri::State<'_, SharedState>,
    web_config: WebManagementConfig,
) -> Result<String, String> {
    let mut proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    proxy_state.web_management = web_config;
    log_audit_event("config_change", "Web管理配置已更新", None);
    Ok("Web管理配置已更新".to_string())
}

// Tauri 命令：获取负载均衡状态
#[tauri::command]
async fn get_load_balance_state(state: tauri::State<'_, SharedState>) -> Result<LoadBalanceState, String> {
    let proxy_state = state.lock().map_err(|e| format!("状态锁定失败: {}", e))?;
    Ok(proxy_state.load_balance_state.clone())
}

// 代理服务器主函数
async fn run_proxy_server(listen_addr: &str, config: ProxyConfig) -> Result<()> {
    let listener = TcpListener::bind(listen_addr).await?;
    println!("代理服务器监听: {}", listen_addr);

    loop {
        let (client_stream, client_addr) = listener.accept().await?;
        println!("新连接来自: {}", client_addr);

        // 访问控制检查
        let client_ip = client_addr.ip().to_string();
        if !is_access_allowed(&client_ip) {
            println!("拒绝连接: {} (访问控制)", client_addr);
            continue;
        }

        let config_clone = config.clone();
        tokio::spawn(async move {
            if let Err(e) = handle_client(client_stream, config_clone).await {
                eprintln!("处理客户端连接错误: {}", e);
            }
        });
    }
}

// 处理客户端连接
async fn handle_client(mut client_stream: TcpStream, config: ProxyConfig) -> Result<()> {
    let client_addr = client_stream.peer_addr()?;
    let client_ip = client_addr.ip().to_string();

    let mut buffer = [0; 4096];
    let n = client_stream.read(&mut buffer).await?;

    if n == 0 {
        return Ok(());
    }

    let request = String::from_utf8_lossy(&buffer[..n]);

    // 解析 HTTP CONNECT 请求
    if request.starts_with("CONNECT") {
        if let Err(e) = handle_connect_request(client_stream, &request, config.clone()).await {
            log_connection(&client_ip, "unknown", 0, &config.proxy_type, "failed");
            return Err(e);
        }
        log_connection(&client_ip, "connect", 0, &config.proxy_type, "connected");
    } else {
        // 处理普通 HTTP 请求
        if let Err(e) = handle_http_request(client_stream, &request, config.clone()).await {
            log_connection(&client_ip, "unknown", 0, &config.proxy_type, "failed");
            return Err(e);
        }
        log_connection(&client_ip, "http", 80, &config.proxy_type, "connected");
    }

    Ok(())
}

// 处理 CONNECT 请求（用于 HTTPS）
async fn handle_connect_request(mut client_stream: TcpStream, request: &str, config: ProxyConfig) -> Result<()> {
    let lines: Vec<&str> = request.lines().collect();
    if lines.is_empty() {
        return Err(anyhow::anyhow!("无效的 CONNECT 请求"));
    }

    let first_line = lines[0];
    let parts: Vec<&str> = first_line.split_whitespace().collect();
    if parts.len() < 2 {
        return Err(anyhow::anyhow!("无效的 CONNECT 请求格式"));
    }

    let target_addr = parts[1];

    // 连接到目标服务器（通过上游代理）
    let mut target_stream = connect_through_proxy(target_addr, &config).await?;

    // 发送 200 Connection Established 响应
    client_stream.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await?;

    // 开始双向数据转发
    tokio::spawn(async move {
        let _ = tokio::io::copy_bidirectional(&mut client_stream, &mut target_stream).await;
    });

    Ok(())
}

// 处理普通 HTTP 请求
async fn handle_http_request(mut client_stream: TcpStream, request: &str, config: ProxyConfig) -> Result<()> {
    // 解析请求获取目标主机
    let lines: Vec<&str> = request.lines().collect();
    let mut host = String::new();

    for line in &lines {
        if line.to_lowercase().starts_with("host:") {
            host = line[5..].trim().to_string();
            break;
        }
    }

    if host.is_empty() {
        return Err(anyhow::anyhow!("无法找到 Host 头"));
    }

    // 连接到目标服务器（通过上游代理）
    let target_addr = if host.contains(':') { host } else { format!("{}:80", host) };
    let mut target_stream = connect_through_proxy(&target_addr, &config).await?;

    // 转发原始请求
    target_stream.write_all(request.as_bytes()).await?;

    // 开始双向数据转发
    tokio::spawn(async move {
        let _ = tokio::io::copy_bidirectional(&mut client_stream, &mut target_stream).await;
    });

    Ok(())
}

// 通过上游代理连接到目标服务器
async fn connect_through_proxy(target_addr: &str, config: &ProxyConfig) -> Result<TcpStream> {
    // 如果有代理链，使用代理链连接
    if let Some(chain) = &config.chain {
        if !chain.is_empty() {
            return connect_through_proxy_chain(target_addr, chain).await;
        }
    }

    // 如果有负载均衡服务器，使用负载均衡
    if let Some(servers) = &config.load_balance_servers {
        if !servers.is_empty() {
            return connect_through_load_balance(target_addr, config, servers).await;
        }
    }

    // 否则使用单个代理连接
    connect_through_single_proxy(target_addr, config).await
}

// 通过负载均衡连接到目标服务器
async fn connect_through_load_balance(target_addr: &str, config: &ProxyConfig, servers: &[ProxyNode]) -> Result<TcpStream> {
    // 根据负载均衡策略选择服务器
    let selected_server = match config.load_balance_strategy.as_deref().unwrap_or("round_robin") {
        "round_robin" => select_server_round_robin(servers),
        "random" => select_server_random(servers),
        "least_connections" => select_server_least_connections(servers),
        _ => select_server_round_robin(servers), // 默认使用轮询
    };

    // 尝试连接选中的服务器
    match connect_to_proxy_node(&selected_server).await {
        Ok(mut stream) => {
            if let Ok(()) = establish_connection_through_proxy(&mut stream, target_addr, &selected_server).await {
                return Ok(stream);
            }
        }
        Err(_) => {
            // 如果选中的服务器失败，使用故障转移机制
            return connect_with_failover(target_addr, servers).await;
        }
    }

    // 如果所有方法都失败，使用故障转移机制
    connect_with_failover(target_addr, servers).await
}

// 轮询选择服务器
fn select_server_round_robin(servers: &[ProxyNode]) -> ProxyNode {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static COUNTER: AtomicUsize = AtomicUsize::new(0);

    let index = COUNTER.fetch_add(1, Ordering::Relaxed) % servers.len();
    servers[index].clone()
}

// 随机选择服务器
fn select_server_random(servers: &[ProxyNode]) -> ProxyNode {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let index = rng.gen_range(0..servers.len());
    servers[index].clone()
}

// 选择连接数最少的服务器（简化实现）
fn select_server_least_connections(servers: &[ProxyNode]) -> ProxyNode {
    // 简化实现：使用轮询算法，在实际应用中应该维护真实的连接计数
    // 这里为了演示目的，我们使用一个简单的基于服务器索引的选择
    use std::sync::atomic::{AtomicUsize, Ordering};
    static COUNTER: AtomicUsize = AtomicUsize::new(0);

    // 模拟选择连接数最少的服务器（实际上是轮询）
    let index = COUNTER.fetch_add(1, Ordering::Relaxed) % servers.len();
    servers[index].clone()
}

// 健康检查函数
async fn check_server_health(server: &ProxyNode) -> ServerHealth {
    let start_time = std::time::Instant::now();
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();

    let mut health = ServerHealth {
        host: server.host.clone(),
        port: server.port,
        is_healthy: false,
        last_check: now,
        failure_count: 0,
        response_time: 0,
    };

    // 尝试连接服务器
    match tokio::time::timeout(
        std::time::Duration::from_secs(5),
        TcpStream::connect(format!("{}:{}", server.host, server.port))
    ).await {
        Ok(Ok(_)) => {
            health.is_healthy = true;
            health.response_time = start_time.elapsed().as_millis() as u64;
        }
        Ok(Err(_)) | Err(_) => {
            health.is_healthy = false;
            health.failure_count = 1;
            health.response_time = 5000; // 超时时间
        }
    }

    health
}

// 选择健康的服务器
fn select_healthy_server(servers: &[ProxyNode], health_states: &[ServerHealth]) -> Option<ProxyNode> {
    // 过滤出健康的服务器
    let healthy_servers: Vec<&ProxyNode> = servers.iter()
        .enumerate()
        .filter(|(i, _)| {
            health_states.get(*i).map_or(true, |h| h.is_healthy)
        })
        .map(|(_, server)| server)
        .collect();

    if healthy_servers.is_empty() {
        return None;
    }

    // 从健康的服务器中选择一个
    Some(select_server_round_robin(&healthy_servers.into_iter().cloned().collect::<Vec<_>>()))
}

// 带故障转移的代理连接
async fn connect_with_failover(target_addr: &str, servers: &[ProxyNode]) -> Result<TcpStream> {
    let mut last_error = None;

    // 检查所有服务器的健康状态
    let mut health_checks = Vec::new();
    for server in servers {
        health_checks.push(check_server_health(server).await);
    }

    // 尝试连接健康的服务器
    if let Some(selected_server) = select_healthy_server(servers, &health_checks) {
        match connect_to_proxy_node(&selected_server).await {
            Ok(mut stream) => {
                if let Ok(()) = establish_connection_through_proxy(&mut stream, target_addr, &selected_server).await {
                    return Ok(stream);
                }
            }
            Err(e) => last_error = Some(e),
        }
    }

    // 如果所有健康服务器都失败，尝试所有服务器
    for server in servers {
        match connect_to_proxy_node(server).await {
            Ok(mut stream) => {
                if let Ok(()) = establish_connection_through_proxy(&mut stream, target_addr, server).await {
                    return Ok(stream);
                }
            }
            Err(e) => last_error = Some(e),
        }
    }

    Err(last_error.unwrap_or_else(|| anyhow::anyhow!("所有代理服务器都不可用")))
}

// 通过代理链连接到目标服务器
async fn connect_through_proxy_chain(target_addr: &str, chain: &[ProxyNode]) -> Result<TcpStream> {
    if chain.is_empty() {
        return Err(anyhow::anyhow!("代理链为空"));
    }

    // 连接到第一个代理
    let first_proxy = &chain[0];
    let mut stream = connect_to_proxy_node(first_proxy).await?;

    // 如果只有一个代理，直接连接目标
    if chain.len() == 1 {
        establish_connection_through_proxy(&mut stream, target_addr, first_proxy).await?;
        return Ok(stream);
    }

    // 通过代理链建立连接
    for (i, proxy) in chain.iter().enumerate().skip(1) {
        let next_addr = format!("{}:{}", proxy.host, proxy.port);

        // 通过当前代理连接到下一个代理
        establish_connection_through_proxy(&mut stream, &next_addr, &chain[i-1]).await?;

        // 如果这是最后一个代理，连接到目标
        if i == chain.len() - 1 {
            establish_connection_through_proxy(&mut stream, target_addr, proxy).await?;
        }
    }

    Ok(stream)
}

// 连接到单个代理节点
async fn connect_to_proxy_node(proxy: &ProxyNode) -> Result<TcpStream> {
    let proxy_addr = format!("{}:{}", proxy.host, proxy.port);
    TcpStream::connect(&proxy_addr).await
        .map_err(|e| anyhow::anyhow!("连接代理失败 {}: {}", proxy_addr, e))
}

// 通过单个代理连接到目标服务器
async fn connect_through_single_proxy(target_addr: &str, config: &ProxyConfig) -> Result<TcpStream> {
    let proxy_addr = format!("{}:{}", config.host, config.port);
    let mut proxy_stream = TcpStream::connect(&proxy_addr).await?;

    let proxy_config = ProxyConfig {
        host: config.host.clone(),
        port: config.port,
        username: config.username.clone(),
        password: config.password.clone(),
        proxy_type: config.proxy_type.clone(),
        chain: None,
        load_balance_servers: None,
        load_balance_strategy: None,
        enable_tls: None,
        tls_verify_cert: None,
        dns_leak_protection: None,
        custom_dns_servers: None,
    };

    establish_connection_through_proxy(&mut proxy_stream, target_addr, &proxy_node_from_config(&proxy_config)).await?;
    Ok(proxy_stream)
}

// 将ProxyConfig转换为ProxyNode
fn proxy_node_from_config(config: &ProxyConfig) -> ProxyNode {
    ProxyNode {
        host: config.host.clone(),
        port: config.port,
        username: config.username.clone(),
        password: config.password.clone(),
        proxy_type: config.proxy_type.clone(),
    }
}

// 通过代理建立连接的通用函数
async fn establish_connection_through_proxy(stream: &mut TcpStream, target_addr: &str, proxy: &ProxyNode) -> Result<()> {
    match proxy.proxy_type.as_str() {
        "http" => {
            // HTTP 代理连接
            let connect_request = format!(
                "CONNECT {} HTTP/1.1\r\nHost: {}\r\n",
                target_addr, target_addr
            );

            // 如果有认证信息，添加 Proxy-Authorization 头
            let auth_header = if let (Some(username), Some(password)) = (&proxy.username, &proxy.password) {
                use base64::Engine;
                let credentials = base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", username, password));
                format!("Proxy-Authorization: Basic {}\r\n", credentials)
            } else {
                String::new()
            };

            let full_request = format!("{}{}\r\n", connect_request, auth_header);
            stream.write_all(full_request.as_bytes()).await?;

            // 读取代理服务器响应
            let mut response = [0; 1024];
            let n = stream.read(&mut response).await?;
            let response_str = String::from_utf8_lossy(&response[..n]);

            if !response_str.contains("200") {
                return Err(anyhow::anyhow!("代理连接失败: {}", response_str));
            }
        }
        "socks5" => {
            // SOCKS5 代理连接
            // 发送认证方法选择
            let auth_methods = if proxy.username.is_some() && proxy.password.is_some() {
                vec![0x05, 0x02, 0x00, 0x02] // 支持无认证和用户名/密码认证
            } else {
                vec![0x05, 0x01, 0x00] // 仅支持无认证
            };

            stream.write_all(&auth_methods).await?;

            // 读取服务器选择的认证方法
            let mut response = [0; 2];
            stream.read_exact(&mut response).await?;

            if response[0] != 0x05 {
                return Err(anyhow::anyhow!("无效的 SOCKS5 响应"));
            }

            // 处理认证
            match response[1] {
                0x00 => {
                    // 无需认证
                }
                0x02 => {
                    // 用户名/密码认证
                    if let (Some(username), Some(password)) = (&proxy.username, &proxy.password) {
                        let mut auth_request = vec![0x01]; // 认证版本
                        auth_request.push(username.len() as u8);
                        auth_request.extend_from_slice(username.as_bytes());
                        auth_request.push(password.len() as u8);
                        auth_request.extend_from_slice(password.as_bytes());

                        stream.write_all(&auth_request).await?;

                        let mut auth_response = [0; 2];
                        stream.read_exact(&mut auth_response).await?;

                        if auth_response[1] != 0x00 {
                            return Err(anyhow::anyhow!("SOCKS5 认证失败"));
                        }
                    } else {
                        return Err(anyhow::anyhow!("SOCKS5 需要用户名和密码"));
                    }
                }
                _ => {
                    return Err(anyhow::anyhow!("不支持的 SOCKS5 认证方法"));
                }
            }

            // 发送连接请求
            let (host, port) = parse_host_port(target_addr)?;
            let mut connect_request = vec![0x05, 0x01, 0x00]; // 版本、连接命令、保留字段

            // 地址类型和地址
            if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() {
                connect_request.push(0x01); // IPv4
                connect_request.extend_from_slice(&ip.octets());
            } else {
                connect_request.push(0x03); // 域名
                connect_request.push(host.len() as u8);
                connect_request.extend_from_slice(host.as_bytes());
            }

            // 端口
            connect_request.extend_from_slice(&port.to_be_bytes());

            stream.write_all(&connect_request).await?;

            // 读取连接响应
            let mut connect_response = [0; 10];
            stream.read(&mut connect_response).await?;

            if connect_response[1] != 0x00 {
                return Err(anyhow::anyhow!("SOCKS5 连接失败"));
            }
        }
        _ => {
            return Err(anyhow::anyhow!("不支持的代理类型: {}", proxy.proxy_type));
        }
    }

    Ok(())
}

// 解析主机和端口
fn parse_host_port(addr: &str) -> Result<(String, u16)> {
    if let Some(pos) = addr.rfind(':') {
        let host = addr[..pos].to_string();
        let port = addr[pos + 1..].parse::<u16>()?;
        Ok((host, port))
    } else {
        Ok((addr.to_string(), 80))
    }
}

// 测试代理连接
async fn test_proxy(config: &ProxyConfig) -> Result<String> {
    use std::time::{Duration, Instant};

    let start_time = Instant::now();
    let proxy_addr = format!("{}:{}", config.host, config.port);

    // 首先测试基本连接
    let stream = tokio::time::timeout(
        Duration::from_secs(10),
        TcpStream::connect(&proxy_addr)
    ).await;

    match stream {
        Ok(Ok(mut stream)) => {
            let connect_time = start_time.elapsed();

            // 测试代理协议
            match config.proxy_type.as_str() {
                "http" => {
                    // 测试HTTP代理
                    let test_request = "CONNECT httpbin.org:80 HTTP/1.1\r\nHost: httpbin.org:80\r\n";

                    // 如果有认证信息，添加认证头
                    let auth_header = if let (Some(username), Some(password)) = (&config.username, &config.password) {
                        use base64::Engine;
                        let credentials = base64::engine::general_purpose::STANDARD.encode(format!("{}:{}", username, password));
                        format!("Proxy-Authorization: Basic {}\r\n", credentials)
                    } else {
                        String::new()
                    };

                    let full_request = format!("{}{}\r\n", test_request, auth_header);

                    if let Err(_) = stream.write_all(full_request.as_bytes()).await {
                        return Err(anyhow::anyhow!("发送测试请求失败"));
                    }

                    // 读取响应
                    let mut response = [0; 1024];
                    match tokio::time::timeout(Duration::from_secs(5), stream.read(&mut response)).await {
                        Ok(Ok(n)) if n > 0 => {
                            let response_str = String::from_utf8_lossy(&response[..n]);
                            if response_str.contains("200") {
                                Ok(format!("HTTP代理连接成功 (延迟: {}ms)", connect_time.as_millis()))
                            } else if response_str.contains("407") {
                                Err(anyhow::anyhow!("代理需要认证"))
                            } else {
                                Err(anyhow::anyhow!("代理响应异常: {}", response_str.lines().next().unwrap_or("未知错误")))
                            }
                        }
                        Ok(Ok(_)) => Err(anyhow::anyhow!("代理无响应")),
                        Ok(Err(e)) => Err(anyhow::anyhow!("读取响应失败: {}", e)),
                        Err(_) => Err(anyhow::anyhow!("代理响应超时")),
                    }
                }
                "socks5" => {
                    // 测试SOCKS5代理
                    // 发送认证方法选择
                    let auth_methods = if config.username.is_some() && config.password.is_some() {
                        vec![0x05, 0x02, 0x00, 0x02] // 支持无认证和用户名/密码认证
                    } else {
                        vec![0x05, 0x01, 0x00] // 仅支持无认证
                    };

                    if let Err(_) = stream.write_all(&auth_methods).await {
                        return Err(anyhow::anyhow!("发送SOCKS5认证方法失败"));
                    }

                    // 读取服务器选择的认证方法
                    let mut response = [0; 2];
                    match tokio::time::timeout(Duration::from_secs(5), stream.read_exact(&mut response)).await {
                        Ok(Ok(_)) => {
                            if response[0] != 0x05 {
                                return Err(anyhow::anyhow!("无效的SOCKS5响应"));
                            }

                            // 处理认证
                            match response[1] {
                                0x00 => {
                                    // 无需认证，测试成功
                                    Ok(format!("SOCKS5代理连接成功 (延迟: {}ms)", connect_time.as_millis()))
                                }
                                0x02 => {
                                    // 需要用户名/密码认证
                                    if let (Some(username), Some(password)) = (&config.username, &config.password) {
                                        let mut auth_request = vec![0x01]; // 认证版本
                                        auth_request.push(username.len() as u8);
                                        auth_request.extend_from_slice(username.as_bytes());
                                        auth_request.push(password.len() as u8);
                                        auth_request.extend_from_slice(password.as_bytes());

                                        if let Err(_) = stream.write_all(&auth_request).await {
                                            return Err(anyhow::anyhow!("发送SOCKS5认证信息失败"));
                                        }

                                        let mut auth_response = [0; 2];
                                        match tokio::time::timeout(Duration::from_secs(5), stream.read_exact(&mut auth_response)).await {
                                            Ok(Ok(_)) => {
                                                if auth_response[1] == 0x00 {
                                                    Ok(format!("SOCKS5代理连接成功 (延迟: {}ms)", connect_time.as_millis()))
                                                } else {
                                                    Err(anyhow::anyhow!("SOCKS5认证失败"))
                                                }
                                            }
                                            Ok(Err(e)) => Err(anyhow::anyhow!("读取认证响应失败: {}", e)),
                                            Err(_) => Err(anyhow::anyhow!("认证响应超时")),
                                        }
                                    } else {
                                        Err(anyhow::anyhow!("SOCKS5需要用户名和密码"))
                                    }
                                }
                                0xFF => Err(anyhow::anyhow!("SOCKS5代理拒绝连接")),
                                _ => Err(anyhow::anyhow!("不支持的SOCKS5认证方法")),
                            }
                        }
                        Ok(Err(e)) => Err(anyhow::anyhow!("读取SOCKS5响应失败: {}", e)),
                        Err(_) => Err(anyhow::anyhow!("SOCKS5响应超时")),
                    }
                }
                _ => Err(anyhow::anyhow!("不支持的代理类型: {}", config.proxy_type)),
            }
        }
        Ok(Err(e)) => Err(anyhow::anyhow!("连接代理服务器失败: {}", e)),
        Err(_) => Err(anyhow::anyhow!("连接超时")),
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    // 初始化日志
    tracing_subscriber::fmt::init();

    let state: SharedState = Arc::new(Mutex::new(ProxyState::default()));

    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_fs::init())
        .manage(state)
        .invoke_handler(tauri::generate_handler![
            start_proxy,
            stop_proxy,
            set_system_proxy_settings,
            get_system_proxy_settings,
            test_proxy_connection,
            get_traffic_stats,
            reset_traffic_stats,
            check_servers_health,
            set_auto_launch,
            get_auto_launch_status,
            get_connection_logs,
            get_audit_logs,
            clear_connection_logs,
            clear_audit_logs,
            get_access_control,
            update_access_control,
            get_web_management_config,
            update_web_management_config,
            get_load_balance_state,
            config_manager::save_proxy_config,
            config_manager::load_proxy_configs,
            config_manager::delete_proxy_config,
            config_manager::get_last_used_proxy,
            config_manager::save_app_settings,
            config_manager::get_app_settings,
            config_manager::get_preset_configs,
            config_manager::add_preset_config,
            config_manager::delete_preset_config
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
